<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <!-- 搜索区域 -->
          <el-form :inline="true" :model="queryParams" class="search-form compact-form" ref="queryFormRef"
            label-width="80px">
            <el-form-item label="账户代码" prop="accountCode">
              <el-select v-model="queryParams.accountCode" placeholder="请选择账户代码" style="width: 180px" clearable
                @change="handleQuery">
                <el-option v-for="account in accountList" :key="account.accountCode"
                  :label="account.accountCode + ' - ' + account.accountName" :value="account.accountCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker v-model="queryParams.beginDate" type="date" placeholder="请选择开始日期" style="width: 180px"
                clearable />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="queryParams.endDate" type="date" placeholder="请选择结束日期" style="width: 180px"
                clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" size="small" @click="handleQuery">查询</el-button>
              <el-button icon="RefreshRight" size="small" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" size="small" @click="handleAdd"
                v-hasPermi="['kylin:futureAccountDaily:add']">新增</el-button>
              <el-button type="danger" icon="Delete" size="small" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['kylin:futureAccountDaily:delete']">删除</el-button>
              <el-button icon="Download" size="small" @click="handleExport" v-hasPermi="['kylin:futureAccountDaily:export']">导出</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Histogram" size="small" @click="handleShowEquityChart">资金曲线</el-button>
            </el-form-item>
          </el-form>

          <!-- 数据表格 -->
          <el-table v-loading="loading" :data="accountDailyList" @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="账户代码" prop="accountCode" align="center" />
            <el-table-column label="结算日期" prop="settlementDate" align="center" />

            <el-table-column label="当日存取合计" prop="dailyDepositWithdrawal" align="center"
              :formatter="(row) => formatAmount(row.dailyDepositWithdrawal)" />
            <el-table-column label="逐日盯市" align="center">
              <el-table-column label="上日结存" prop="previousBalanceDay" align="center"
                :formatter="(row) => formatAmount(row.previousBalanceDay)" />
              <el-table-column label="当日盈亏" prop="dailyProfitDay" align="center"
                :formatter="(row) => formatAmount(row.dailyProfitDay)" />
              <el-table-column label="当日结存" prop="dailyBalanceDay" align="center"
                :formatter="(row) => formatAmount(row.dailyBalanceDay)" />
            </el-table-column>
            <el-table-column label="逐笔对冲" align="center">
              <el-table-column label="上日结存" prop="previousBalanceTrade" align="center"
                :formatter="(row) => formatAmount(row.previousBalanceTrade)" />
              <el-table-column label="平仓盈亏" prop="closeProfitTrade" align="center"
                :formatter="(row) => formatAmount(row.closeProfitTrade)" />
              <el-table-column label="浮动盈亏" prop="floatProfitTrade" align="center"
                :formatter="(row) => formatAmount(row.floatProfitTrade)" />
              <el-table-column label="当日结存" prop="dailyBalanceTrade" align="center"
                :formatter="(row) => formatAmount(row.dailyBalanceTrade)" />
            </el-table-column>
            <el-table-column label="当日手续费" prop="dailyFee" align="center"
              :formatter="(row) => formatAmount(row.dailyFee)" />
            <el-table-column label="客户权益" prop="equity" align="center" :formatter="(row) => formatAmount(row.equity)" />
            <el-table-column label="保证金占用" prop="marginUsed" align="center"
              :formatter="(row) => formatAmount(row.marginUsed)" />
            <el-table-column label="可用资金" prop="availableFunds" align="center"
              :formatter="(row) => formatAmount(row.availableFunds)" />
            <el-table-column label="风险度" prop="riskRatio" align="center"
              :formatter="(row) => formatRiskRatio(row.riskRatio)" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-button type="primary" link icon="Edit" size="small" @click="handleUpdate(scope.row)"
                  v-hasPermi="['kylin:futureAccountDaily:edit']">修改</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"
            @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="open" :title="title" width="700px" @close="handleClose">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="账户代码" prop="accountCode">
          <el-select v-model="form.accountCode" placeholder="请选择账户代码" style="width: 100%">
            <el-option v-for="account in accountList" :key="account.accountCode" :label="account.accountCode + ' - ' + account.accountName" :value="account.accountCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算日期" prop="settlementDate">
          <el-date-picker v-model="form.settlementDate" type="date" placeholder="请选择结算日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="上日结存(逐日盯市)" prop="previousBalanceDay">
          <el-input v-model.number="form.previousBalanceDay" placeholder="请输入上日结存(逐日盯市)" />
        </el-form-item>
        <el-form-item label="上日结存(逐笔对冲)" prop="previousBalanceTrade">
          <el-input v-model.number="form.previousBalanceTrade" placeholder="请输入上日结存(逐笔对冲)" />
        </el-form-item>
        <el-form-item label="当日存取合计" prop="dailyDepositWithdrawal">
          <el-input v-model.number="form.dailyDepositWithdrawal" placeholder="请输入当日存取合计" />
        </el-form-item>
        <el-form-item label="当日盈亏(逐日盯市)" prop="dailyProfitDay">
          <el-input v-model.number="form.dailyProfitDay" placeholder="请输入当日盈亏(逐日盯市)" />
        </el-form-item>
        <el-form-item label="当日结存(逐日盯市)" prop="dailyBalanceDay">
          <el-input v-model.number="form.dailyBalanceDay" placeholder="请输入当日结存(逐日盯市)" />
        </el-form-item>
        <el-form-item label="平仓盈亏(逐笔对冲)" prop="closeProfitTrade">
          <el-input v-model.number="form.closeProfitTrade" placeholder="请输入平仓盈亏(逐笔对冲)" />
        </el-form-item>
        <el-form-item label="当日结存(逐笔对冲)" prop="dailyBalanceTrade">
          <el-input v-model.number="form.dailyBalanceTrade" placeholder="请输入当日结存(逐笔对冲)" />
        </el-form-item>
        <el-form-item label="浮动盈亏(逐笔对冲)" prop="floatProfitTrade">
          <el-input v-model.number="form.floatProfitTrade" placeholder="请输入浮动盈亏(逐笔对冲)" />
        </el-form-item>
        <el-form-item label="当日手续费" prop="dailyFee">
          <el-input v-model.number="form.dailyFee" placeholder="请输入当日手续费" />
        </el-form-item>
        <el-form-item label="客户权益" prop="equity">
          <el-input v-model.number="form.equity" placeholder="请输入客户权益" />
        </el-form-item>
        <el-form-item label="保证金占用" prop="marginUsed">
          <el-input v-model.number="form.marginUsed" placeholder="请输入保证金占用" />
        </el-form-item>
        <el-form-item label="可用资金" prop="availableFunds">
          <el-input v-model.number="form.availableFunds" placeholder="请输入可用资金" />
        </el-form-item>
        <el-form-item label="风险度" prop="riskRatio">
          <el-input v-model.number="form.riskRatio" placeholder="请输入风险度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资金曲线对话框 -->
    <el-dialog v-model="chartDialogVisible" width="900px" @close="handleChartDialogClose">
      <template #title>
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <span>资金曲线</span>
          <!-- 非全屏模式下显示标题栏中的前复权开关 -->
          <div v-if="!isFullscreen" style="display: flex; align-items: center;">
            <span style="margin-right: 10px;">前复权</span>
            <el-switch v-model="isFilled" @change="toggleFilled"></el-switch>
          </div>
        </div>
      </template>
      <div class="chart-container" :class="{ 'fullscreen': isFullscreen }">
        <div class="chart-header" style="display: flex; align-items: center; justify-content: flex-start;">
          <!-- 全屏模式下在图表头部显示前复权开关 -->
          <div v-if="isFullscreen" style="display: flex; align-items: center; margin-right: 16px;">
            <span style="margin-right: 6px; font-size: 14px;">前复权</span>
            <el-switch v-model="isFilled" @change="toggleFilled" size="small"></el-switch>
          </div>
          <el-button 
            type="text" 
            icon="FullScreen"
            size="small" 
            @click="toggleFullscreen"
            :title="isFullscreen ? '退出全屏' : '全屏显示'"
          ></el-button>
        </div>
        <div id="equityChart" style="width: 100%; height: 400px;"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="FutureAccountDaily">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import Pagination from '@/components/Pagination'
import { listFutureAccountDaily, getFutureAccountDaily, addFutureAccountDaily, updateFutureAccountDaily, delFutureAccountDaily, exportFutureAccountDaily } from '@/api/kylin/futureAccountDaily'
import { getAllFutureAccounts } from '@/api/kylin/futureAccount'

// 金额格式化函数
const formatAmount = (value) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0.00'
  }
  return Number(value).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 风险度格式化函数
const formatRiskRatio = (value) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0.00%'
  }
  return (Number(value) * 100).toFixed(2) + '%'
}

// 加载期货账户列表
const loadAccountList = async () => {
  try {
    const response = await getAllFutureAccounts()
    accountList.value = response?.data || []
  } catch (error) {
    ElMessage.error('获取期货账户列表失败：' + (error.response?.data?.msg || error.message))
  }
}

const router = useRouter()

// 表格数据
const accountDailyList = ref([])
const loading = ref(true)
const total = ref(0)
const isFullscreen = ref(false)

// 分页参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  accountCode: undefined,
  beginDate: undefined,
  endDate: undefined
})

// 期货账户列表
const accountList = ref([])

// 表单相关
const formRef = ref(null)
const queryFormRef = ref(null)
const open = ref(false)
const title = ref('')
const form = reactive({
  id: undefined,
  accountCode: '',
  settlementDate: '',
  previousBalanceDay: 0,
  previousBalanceTrade: 0,
  dailyDepositWithdrawal: 0,
  dailyProfitDay: 0,
  dailyBalanceDay: 0,
  closeProfitTrade: 0,
  dailyBalanceTrade: 0,
  floatProfitTrade: 0,
  dailyFee: 0,
  equity: 0,
  marginUsed: 0,
  availableFunds: 0,
  riskRatio: 0
})
const rules = reactive({
  accountCode: [{ required: true, message: '账户代码不能为空', trigger: 'blur' }],
  settlementDate: [{ required: true, message: '结算日期不能为空', trigger: 'change' }],
  previousBalanceDay: [{ required: true, message: '上日结存(逐日盯市)不能为空', trigger: 'blur' }],
  previousBalanceTrade: [{ required: true, message: '上日结存(逐笔对冲)不能为空', trigger: 'blur' }],
  equity: [{ required: true, message: '期末权益不能为空', trigger: 'blur' }]
})

// 选中的行
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 资金曲线相关
const chartDialogVisible = ref(false)
let equityChart = null
// 前复权相关状态
const isFilled = ref(false)
const originalData = ref(null)
const equityChartData = ref({
    dates: [],
    hyEquity: [],
    hsEquity: [],
    totalEquity: [],
    hyWithdrawalDepositTotal: [],
    hsWithdrawalDepositTotal: []
})
// 保存图例选择状态，避免前复权切换时重置显示的账户
const legendSelectionState = ref({
    'hy账户': true,
    'hs账户': true,
    '合计': true
})

// 列表查询
function getList() {
  loading.value = true
  // 创建查询参数副本，确保日期格式正确
  const params = { ...queryParams }

  // 确保日期参数格式正确，使用本地时间避免时区偏移
  if (params.beginDate && params.beginDate instanceof Date) {
    const date = params.beginDate
    params.beginDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }
  if (params.endDate && params.endDate instanceof Date) {
    const date = params.endDate
    params.endDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }

  // 使用驼峰命名参数
  const transformParams = {
    pageNum: params.pageNum,
    pageSize: params.pageSize,
    accountCode: params.accountCode,
    beginDate: params.beginDate,
    endDate: params.endDate
  }

  console.log('发送到后端的查询参数:', transformParams)

  listFutureAccountDaily(transformParams).then(response => {
    if (response.code === 200) {
      // 兼容不同的数据结构返回格式
      if (response.data && response.data.rows !== undefined) {
        // 标准格式：data包含rows和total
        total.value = response.data.total || 0
        // 直接使用后端返回的驼峰命名数据
        accountDailyList.value = response.data.rows || []
      } else if (response.rows !== undefined) {
        // 直接在response中包含rows和total
        total.value = response.total || 0
        // 直接使用后端返回的驼峰命名数据
        accountDailyList.value = response.rows || []
      } else {
        // 默认情况：清空列表
        accountDailyList.value = []
        total.value = 0
      }
    } else {
      // 状态码不是200时也清空列表
      accountDailyList.value = []
      total.value = 0
      console.warn('获取数据状态码异常:', response.code)
    }
  }).catch(error => {
    console.error('获取期货账户资金日报列表失败:', error)
    ElMessage.error('获取期货账户资金日报列表失败，请稍后重试')
    // 发生错误时也清空列表
    accountDailyList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
  })
}

// 搜索
async function handleQuery() {
  queryParams.pageNum = 1
  // 确保日期参数正确格式化，使用本地时间避免时区偏移
  if (queryParams.beginDate && queryParams.beginDate instanceof Date) {
    const date = queryParams.beginDate
    queryParams.beginDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }
  if (queryParams.endDate && queryParams.endDate instanceof Date) {
    const date = queryParams.endDate
    queryParams.endDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }
  console.log('查询参数:', queryParams)
  
  // 先获取列表数据
  getList()
  
  // 如果资金曲线对话框是打开的，自动刷新图表以适应新的查询条件
  if (chartDialogVisible.value) {
    await refreshChartWithNewAccount()
  }
}

// 重置
function resetQuery() {
  // 直接重置查询参数
  queryParams.accountCode = undefined
  queryParams.beginDate = undefined
  queryParams.endDate = undefined
  queryParams.pageNum = 1

  // 重置表单状态
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }

  handleQuery()
}

// 新增
function handleAdd() {
  resetForm()
  open.value = true
  title.value = '新增期货账户资金日报'
}

// 修改
function handleUpdate(row) {
  getFutureAccountDaily(row.id).then(response => {
    if (response.code === 200 && response.data) {
      formRef.value?.resetFields()
      open.value = true
      title.value = '修改期货账户资金日报'
      form.id = response.data.id
      form.accountCode = response.data.accountCode
      form.settlementDate = response.data.settlementDate
      form.previousBalanceDay = response.data.previousBalanceDay
      form.previousBalanceTrade = response.data.previousBalanceTrade
      form.dailyDepositWithdrawal = response.data.dailyDepositWithdrawal
      form.dailyProfitDay = response.data.dailyProfitDay
      form.dailyBalanceDay = response.data.dailyBalanceDay || 0
      form.closeProfitTrade = response.data.closeProfitTrade
      form.dailyBalanceTrade = response.data.dailyBalanceTrade || 0
      form.floatProfitTrade = response.data.floatProfitTrade || 0
      form.dailyFee = response.data.dailyFee
      form.equity = response.data.equity
      form.marginUsed = response.data.marginUsed
      form.availableFunds = response.data.availableFunds
      form.riskRatio = response.data.riskRatio
    }
  }).catch(error => {
    console.error('获取期货账户资金日报详情失败:', error)
    ElMessage.error('获取期货账户资金日报详情失败，请稍后重试')
  })
}

// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  form.id = undefined
  form.accountCode = ''
  form.settlementDate = ''
  form.previousBalanceDay = 0
  form.previousBalanceTrade = 0
  form.dailyDepositWithdrawal = 0
  form.dailyProfitDay = 0
  form.dailyBalanceDay = 0
  form.closeProfitTrade = 0
  form.dailyBalanceTrade = 0
  form.floatProfitTrade = 0
  form.dailyFee = 0
  form.equity = 0
  form.marginUsed = 0
  form.availableFunds = 0
  form.riskRatio = 0
}

// 关闭对话框
function handleClose() {
  open.value = false
  resetForm()
}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 创建表单数据副本并处理日期字段
      const submitData = { ...form }
      // 处理日期字段，确保是字符串类型并只保留YYYY-MM-DD格式
      if (submitData.settlementDate) {
        // 检查是否为Date对象或字符串
        if (typeof submitData.settlementDate === 'object' && submitData.settlementDate instanceof Date) {
          // 如果是Date对象，转换为YYYY-MM-DD格式
          const date = submitData.settlementDate
          submitData.settlementDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
        } else if (typeof submitData.settlementDate === 'string') {
          // 如果是字符串，处理ISO格式日期
          submitData.settlementDate = submitData.settlementDate.split('T')[0]
        }
      }
      const saveAccountDaily = form.id ? updateFutureAccountDaily : addFutureAccountDaily
      saveAccountDaily(submitData).then(response => {
        if (response.code === 200) {
          ElMessage.success('操作成功')
          open.value = false
          getList()
        } else {
          ElMessage.error(response.msg || '操作失败')
        }
      }).catch(error => {
        console.error('保存期货账户资金日报失败:', error)
        ElMessage.error('保存期货账户资金日报失败，请稍后重试')
      })
    }
  })
}

// 选中行变化
function handleSelectionChange(selection) {
  ids.value = selection.map(row => row.id)
  single.value = selection.length <= 1
  multiple.value = !selection.length
}

// 批量删除
function handleDelete() {
  ElMessageBox.confirm(
    '确定要删除选中的期货账户资金日报吗？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 直接传递ids数组作为参数
    return delFutureAccountDaily(ids.value)
  }).then(response => {
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  }).catch(error => {
    if (error === 'cancel') return
    console.error('删除期货账户资金日报失败:', error)
    ElMessage.error('删除期货账户资金日报失败，请稍后重试')
  })
}

// 获取资金曲线数据
async function fetchEquityChartData() {
  try {
    // 创建查询参数副本，确保日期格式正确
    const params = {
      pageNum: 1,
      pageSize: 1000, // 获取足够多的数据用于图表
      accountCode: undefined, // 不限制账户，获取所有账户数据
      beginDate: queryParams.beginDate,
      endDate: queryParams.endDate
    }

    // 确保日期参数格式正确
    if (params.beginDate && params.beginDate instanceof Date) {
      const date = params.beginDate
      params.beginDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }
    if (params.endDate && params.endDate instanceof Date) {
      const date = params.endDate
      params.endDate = `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }

    const response = await listFutureAccountDaily(params)
    if (response.code === 200) {
      const data = response.data?.rows || response.rows || []
      
      // 按日期分组
      const groupedByDate = {}
      data.forEach(item => {
        if (!groupedByDate[item.settlementDate]) {
          groupedByDate[item.settlementDate] = {
            hy: 0,
            hs: 0,
            hyWithdrawalDeposit: 0,
            hsWithdrawalDeposit: 0
          }
        }
        if (item.accountCode === 'hy') {
          groupedByDate[item.settlementDate].hy = Number(item.equity) || 0
          groupedByDate[item.settlementDate].hyWithdrawalDeposit = Number(item.dailyDepositWithdrawal) || 0
        } else if (item.accountCode === 'hs') {
          groupedByDate[item.settlementDate].hs = Number(item.equity) || 0
          groupedByDate[item.settlementDate].hsWithdrawalDeposit = Number(item.dailyDepositWithdrawal) || 0
        }
      })

      // 转换为数组并排序
      const dates = Object.keys(groupedByDate).sort()
      const hyEquity = []
      const hsEquity = []
      const totalEquity = []
      const hyWithdrawalDepositTotal = []
      const hsWithdrawalDepositTotal = []

      dates.forEach(date => {
        hyEquity.push(groupedByDate[date].hy)
        hsEquity.push(groupedByDate[date].hs)
        totalEquity.push(groupedByDate[date].hy + groupedByDate[date].hs)
        hyWithdrawalDepositTotal.push(groupedByDate[date].hyWithdrawalDeposit)
        hsWithdrawalDepositTotal.push(groupedByDate[date].hsWithdrawalDeposit)
      })

      // 保存原始数据
      originalData.value = {
        dates: [...dates],
        hyEquity: [...hyEquity],
        hsEquity: [...hsEquity],
        totalEquity: [...totalEquity],
        hyWithdrawalDepositTotal: [...hyWithdrawalDepositTotal],
        hsWithdrawalDepositTotal: [...hsWithdrawalDepositTotal]
      }

      equityChartData.value = {
        dates,
        hyEquity,
        hsEquity,
        totalEquity,
        hyWithdrawalDepositTotal,
        hsWithdrawalDepositTotal
      }

      return true
    }
    return false
  } catch (error) {
    console.error('获取资金曲线数据失败:', error)
    ElMessage.error('获取资金曲线数据失败，请稍后重试')
    return false
  }
}

// 初始化资金曲线图表
function initEquityChart() {
  if (equityChart) {
    equityChart.dispose()
  }

  const chartDom = document.getElementById('equityChart')
  if (!chartDom) return

  equityChart = echarts.init(chartDom)

  // 计算Y轴的动态范围，使曲线变化更加明显
  console.log('初始化图表，当前数据:', equityChartData.value);
  
  // 收集当前可见系列的数据（基于保存的图例选择状态）
  const visibleValues = [];
  if (legendSelectionState.value['hy账户']) {
    visibleValues.push(...equityChartData.value.hyEquity);
  }
  if (legendSelectionState.value['hs账户']) {
    visibleValues.push(...equityChartData.value.hsEquity);
  }
  if (legendSelectionState.value['合计']) {
    visibleValues.push(...equityChartData.value.totalEquity);
  }
  console.log('初始化图表时的可见数据:', visibleValues);
  
  // 处理空数据情况
  if (visibleValues.length === 0 || visibleValues.every(v => v === 0)) {
    // 如果没有有效数据，设置默认范围
    const option = {
      title: {
        text: '客户权益变化趋势',
        left: 'center',
        textStyle: {
          fontWeight: 'bold',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
          data: ['hy账户', 'hs账户', '合计'],
          bottom: 0,
          textStyle: {
            fontSize: 12
          },
          selected: legendSelectionState.value // 应用保存的图例选择状态
        },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: equityChartData.value.dates || [],
        axisLabel: {
          rotate: 45,
          fontSize: 11
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: function(value) {
            return formatAmount(value)
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            opacity: 0.6
          }
        }
      },
      series: []
    };
    
    equityChart.setOption(option, true); // 使用true强制重绘
    
    console.log('空数据图表初始化完成');
    return;
  }
  
  const minValue = Math.min(...visibleValues);
  const maxValue = Math.max(...visibleValues);
  const range = maxValue - minValue;
  console.log('初始化图表计算的最小值、最大值和范围:', {minValue, maxValue, range});
  
  // 重要改进：确保Y轴范围更加精确和动态
  // 如果数据范围很小，需要特别处理以避免范围过大或过小
  let yAxisMin, yAxisMax;
  
  if (range === 0) {
    // 处理所有值都相同的情况
    const baseValue = minValue || 10000; // 避免0值
    yAxisMin = baseValue * 0.9; // 向下10%
    yAxisMax = baseValue * 1.1; // 向上10%
  } else {
    // 根据数据变化幅度动态调整扩展比例
    const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
    
    if (variationRatio < 0.01) { // 变化小于1%
      // 数据变化非常小，需要更大的扩展比例
      yAxisMin = minValue - range * 0.5; // 向下50%
      yAxisMax = maxValue + range * 0.5; // 向上50%
    } else if (variationRatio < 0.05) { // 变化小于5%
      // 数据变化较小，适度扩展
      yAxisMin = minValue - range * 0.3; // 向下30%
      yAxisMax = maxValue + range * 0.3; // 向上30%
    } else {
      // 正常数据范围
      yAxisMin = minValue - range * 0.1; // 向下10%
      yAxisMax = maxValue + range * 0.1; // 向上10%
    }
  }
  
  // 确保最小值不会小于0
  yAxisMin = Math.max(0, yAxisMin);
  
  console.log('计算的Y轴范围:', {minValue, maxValue, range, yAxisMin, yAxisMax});

  const option = {
    title: {
      text: '客户权益变化趋势',
      left: 'center',
      textStyle: {
        fontWeight: 'bold',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(param => {
          result += param.marker + param.seriesName + ': ' + formatAmount(param.value) + '<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['hy账户', 'hs账户', '合计'],
      bottom: 0,
      textStyle: {
        fontSize: 12
      },
      selected: legendSelectionState.value // 应用保存的图例选择状态
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: equityChartData.value.dates,
      axisLabel: {
        rotate: 45,
        fontSize: 11
      }
    },
    yAxis: {
      type: 'value',
      min: yAxisMin,
      max: yAxisMax,
      axisLabel: {
        formatter: function(value) {
          return formatAmount(value)
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          opacity: 0.6
        }
      }
    },
    // 添加动画效果
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut',
    series: [
      {
        name: 'hy账户',
        type: 'line',
        data: equityChartData.value.hyEquity,
        smooth: false, // 减少平滑，使变化更明显
        lineStyle: {
          width: 3, // 增加线条宽度
          color: '#5470c6'
        },
        // 添加点标记
        symbol: 'circle',
        symbolSize: 4,
        // 添加面积填充，增强视觉效果
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              {offset: 0, color: 'rgba(84, 112, 198, 0.3)'},
              {offset: 1, color: 'rgba(84, 112, 198, 0.05)'}
            ]
          }
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderWidth: 3,
            borderColor: '#fff'
          }
        }
      },
      {
        name: 'hs账户',
        type: 'line',
        data: equityChartData.value.hsEquity,
        smooth: false,
        lineStyle: {
          width: 3,
          color: '#91cc75'
        },
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              {offset: 0, color: 'rgba(145, 204, 117, 0.3)'},
              {offset: 1, color: 'rgba(145, 204, 117, 0.05)'}
            ]
          }
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderWidth: 3,
            borderColor: '#fff'
          }
        }
      },
      {
        name: '合计',
        type: 'line',
        data: equityChartData.value.totalEquity,
        smooth: true,
        lineStyle: {
          width: 4,
          type: 'solid',
          color: '#ee6666'
        },
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          borderWidth: 2,
          borderColor: '#fff'
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderWidth: 4,
            borderColor: '#fff'
          }
        }
      }
    ]
  }

  // 使用true参数强制完全替换当前option，避免ECharts可能的缓存问题
  equityChart.setOption(option, true)

  console.log('图表初始化完成，Y轴范围已设置');

  // 添加图例点击事件监听，实现显示状态变化时动态调整Y轴范围
  equityChart.off('legendselectchanged');
  equityChart.on('legendselectchanged', handleLegendSelectChanged);

  // 响应式调整 - 移除之前可能添加的监听器，避免重复添加
  window.removeEventListener('resize', handleResize)
  window.addEventListener('resize', handleResize)
}

// 防抖动计时器引用
let handleLegendSelectTimeout = null;

// 单独的调整大小处理函数 - 采用更安全的错误处理策略
function handleResize() {
  // 安全检查：确保图表实例存在且resize方法可用
  if (!equityChart || typeof equityChart.resize !== 'function') {
    console.log('handleResize: 图表实例未初始化，跳过resize操作');
    return;
  }
  
  try {
    equityChart.resize();
    console.log('handleResize: resize操作成功完成');
  } catch (e) {
    console.error('handleResize: resize操作失败，将尝试重新初始化图表:', e);
    
    // 发生错误时，尝试安全地重新初始化图表
    try {
      // 先安全地销毁现有图表
      equityChart.dispose();
      equityChart = null;
      
      // 重新获取图表容器并初始化
      const chartDom = document.getElementById('equityChart');
      if (chartDom) {
        equityChart = echarts.init(chartDom);
        // 重新初始化图表配置
        initEquityChart();
        console.log('handleResize: 图表成功重新初始化');
      }
    } catch (reInitError) {
      console.error('handleResize: 图表重新初始化失败:', reInitError);
    }
  }
}

// 处理图例选择变化，采用安全的方式只更新选择状态而不直接修改图表配置
function handleLegendSelectChanged(params) {
  console.log('handleLegendSelectChanged 被调用，开始安全处理');
  
  // 1. 移除所有可能导致图表状态不一致的操作
  // 2. 仅保留必要的图例选择状态更新
  // 3. 避免直接修改Y轴范围和调用resize
  
  // 基础参数验证
  if (!params || typeof params !== 'object' || !params.selected) {
    console.error('handleLegendSelectChanged: 参数无效');
    return;
  }
  
  // 安全更新图例选择状态到Vue响应式数据中
  try {
    // 深拷贝选择状态，避免直接引用可能导致的问题
    const newSelectionState = JSON.parse(JSON.stringify(params.selected));
    Object.assign(legendSelectionState.value, newSelectionState);
    console.log('handleLegendSelectChanged: 图例选择状态已更新');
  } catch (e) {
    console.error('handleLegendSelectChanged: 更新选择状态失败:', e);
  }
  
  // 添加延迟，避免频繁更新Y轴范围
  if (handleLegendSelectTimeout) {
    clearTimeout(handleLegendSelectTimeout);
  }
  
  handleLegendSelectTimeout = setTimeout(() => {
    console.log('延迟执行图例选择后的Y轴范围调整');
    
    // 确保图表实例存在
    if (!equityChart) {
      console.warn('图例选择后调整Y轴范围：图表实例不存在');
      return;
    }
    
    // 收集当前可见系列的数据
    const visibleValues = [];
    if (legendSelectionState.value['hy账户']) {
      visibleValues.push(...equityChartData.value.hyEquity);
    }
    if (legendSelectionState.value['hs账户']) {
      visibleValues.push(...equityChartData.value.hsEquity);
    }
    if (legendSelectionState.value['合计']) {
      visibleValues.push(...equityChartData.value.totalEquity);
    }
    
    console.log('图例选择后的可见数据:', visibleValues);
    
    // 如果有可见数据，重新计算Y轴范围
    if (visibleValues.length > 0 && !visibleValues.every(v => v === 0)) {
      // 基于可见数据重新计算Y轴范围
      const minValue = Math.min(...visibleValues);
      const maxValue = Math.max(...visibleValues);
      const range = maxValue - minValue;
      
      // 计算新的Y轴范围
      let yAxisMin, yAxisMax;
      
      if (range === 0) {
        // 处理所有值都相同的情况
        const baseValue = minValue || 10000; // 避免0值
        yAxisMin = baseValue * 0.9; // 向下10%
        yAxisMax = baseValue * 1.1; // 向上10%
      } else {
        // 根据数据变化幅度动态调整扩展比例
        const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
        
        if (variationRatio < 0.01) { // 变化小于1%
          // 数据变化非常小，需要更大的扩展比例
          yAxisMin = minValue - range * 0.5; // 向下50%
          yAxisMax = maxValue + range * 0.5; // 向上50%
        } else if (variationRatio < 0.05) { // 变化小于5%
          // 数据变化较小，适度扩展
          yAxisMin = minValue - range * 0.3; // 向下30%
          yAxisMax = maxValue + range * 0.3; // 向上30%
        } else {
          // 正常数据范围
          yAxisMin = minValue - range * 0.1; // 向下10%
          yAxisMax = maxValue + range * 0.1; // 向上10%
        }
      }
      
      // 确保最小值不会小于0
      yAxisMin = Math.max(0, yAxisMin);
      
      console.log('图例选择后计算的Y轴范围:', {minValue, maxValue, range, yAxisMin, yAxisMax});
      
      try {
        // 更新图表的Y轴范围
        equityChart.setOption({
          yAxis: {
            min: yAxisMin,
            max: yAxisMax
          }
        }, false); // 使用false避免强制重绘，让ECharts自动处理
        
        console.log('图例选择后的Y轴范围更新成功');
      } catch (updateError) {
        console.error('更新Y轴范围失败:', updateError);
      }
    } else {
      console.log('没有可见数据或所有数据为0，不更新Y轴范围');
    }
  }, 300); // 300ms延迟，避免频繁计算
  // 这些操作会触发ECharts内部状态更新，可能导致coordinateSystem未初始化错误
  // 让ECharts自身处理图例切换后的显示逻辑
  console.log('handleLegendSelectChanged: 处理完成，避免直接修改图表状态');
}

// 计算前复权值
function calculateForwardFilled() {
  if (!originalData.value || !originalData.value.dates || originalData.value.dates.length === 0) {
    console.log('原始数据为空，无法计算前复权');
    return null;
  }
  
  const dates = [...originalData.value.dates]
  const hyEquity = [...originalData.value.hyEquity]
  const hsEquity = [...originalData.value.hsEquity]
  const totalEquity = [...originalData.value.totalEquity]
  const hyWithdrawalDepositTotal = [...originalData.value.hyWithdrawalDepositTotal]
  const hsWithdrawalDepositTotal = [...originalData.value.hsWithdrawalDepositTotal]
  
  console.log('开始计算前复权，数据长度:', dates.length);
  
  // 从后往前计算调整量
  let hyAdjustment = 0
  let hsAdjustment = 0
  
  for (let i = dates.length - 1; i >= 0; i--) {
    // 先保存当前的存取款
    const currentHyWithdrawal = hyWithdrawalDepositTotal[i] || 0
    const currentHsWithdrawal = hsWithdrawalDepositTotal[i] || 0
    
    console.log(`日期: ${dates[i]}, HY存取款: ${currentHyWithdrawal}, HS存取款: ${currentHsWithdrawal}`);
    
    // 更新调整量（累计后面的存取款，包括当前天的存取款）
    hyAdjustment += currentHyWithdrawal
    hsAdjustment += currentHsWithdrawal
    
    // 应用调整量到当前数据（确保当天的调整量也应用到当天数据）
    // 根据示例：复权值 = 不复权值 - 调整量
    hyEquity[i] -= hyAdjustment
    hsEquity[i] -= hsAdjustment
    totalEquity[i] = hyEquity[i] + hsEquity[i]
    console.log(`调整后 - HY: ${hyEquity[i]}, HS: ${hsEquity[i]}, 总计: ${totalEquity[i]}`);
  }
  
  console.log('前复权计算完成');
  return {
    dates,
    hyEquity,
    hsEquity,
    totalEquity,
    hyWithdrawalDepositTotal,
    hsWithdrawalDepositTotal
  }
}

// 切换前复权状态
function toggleFilled(newValue) {
  console.log('前复权状态变更为:', newValue);
  
  // 手动设置状态，避免v-model绑定的问题
  isFilled.value = newValue;
  
  // 确保原始数据存在且完整
  if (!originalData.value || !originalData.value.dates || originalData.value.dates.length === 0) {
    console.warn('原始数据不完整，无法应用前复权或恢复原始数据');
    return;
  }
  
  if (newValue) {
    // 启用前复权
    try {
      const filledData = calculateForwardFilled();
      if (filledData) {
        // 完全替换equityChartData以确保响应式更新
        equityChartData.value = {
          dates: [...filledData.dates],
          hyEquity: [...filledData.hyEquity],
          hsEquity: [...filledData.hsEquity],
          totalEquity: [...filledData.totalEquity],
          hyWithdrawalDepositTotal: [...filledData.hyWithdrawalDepositTotal],
          hsWithdrawalDepositTotal: [...filledData.hsWithdrawalDepositTotal]
        };
        console.log('已应用前复权数据');
      }
    } catch (error) {
      console.error('计算前复权时出错:', error);
      ElMessage.error('应用前复权失败');
    }
  } else {
    // 恢复原始数据
    try {
      equityChartData.value = {
        dates: [...originalData.value.dates],
        hyEquity: [...originalData.value.hyEquity],
        hsEquity: [...originalData.value.hsEquity],
        totalEquity: [...originalData.value.totalEquity],
        hyWithdrawalDepositTotal: [...originalData.value.hyWithdrawalDepositTotal],
        hsWithdrawalDepositTotal: [...originalData.value.hsWithdrawalDepositTotal]
      };
      console.log('已恢复原始数据');
    } catch (error) {
      console.error('恢复原始数据时出错:', error);
      ElMessage.error('恢复原始数据失败');
    }
  }
  
  // 在数据完全更新后初始化图表
  nextTick(() => {
    initEquityChart();
    console.log('已重新初始化图表');
    
    // 确保图表已初始化，并且有可见数据
    if (equityChart) {
      // 收集当前可见系列的数据（基于保存的图例选择状态）
      const visibleValues = [];
      
      if (legendSelectionState.value['hy账户']) {
        visibleValues.push(...equityChartData.value.hyEquity);
      }
      if (legendSelectionState.value['hs账户']) {
        visibleValues.push(...equityChartData.value.hsEquity);
      }
      if (legendSelectionState.value['合计']) {
        visibleValues.push(...equityChartData.value.totalEquity);
      }
      
      console.log('前复权切换后的可见数据:', visibleValues);
      
      // 如果有可见数据，重新计算Y轴范围
      if (visibleValues.length > 0 && !visibleValues.every(v => v === 0)) {
        // 基于可见数据重新计算Y轴范围
        const minValue = Math.min(...visibleValues);
        const maxValue = Math.max(...visibleValues);
        const range = maxValue - minValue;
        
        // 计算新的Y轴范围
        let yAxisMin, yAxisMax;
        
        if (range === 0) {
          // 处理所有值都相同的情况
          const baseValue = minValue || 10000; // 避免0值
          yAxisMin = baseValue * 0.9; // 向下10%
          yAxisMax = baseValue * 1.1; // 向上10%
        } else {
          // 根据数据变化幅度动态调整扩展比例
          const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
          
          if (variationRatio < 0.01) { // 变化小于1%
            // 数据变化非常小，需要更大的扩展比例
            yAxisMin = minValue - range * 0.5; // 向下50%
            yAxisMax = maxValue + range * 0.5; // 向上50%
          } else if (variationRatio < 0.05) { // 变化小于5%
            // 数据变化较小，适度扩展
            yAxisMin = minValue - range * 0.3; // 向下30%
            yAxisMax = maxValue + range * 0.3; // 向上30%
          } else {
            // 正常数据范围
            yAxisMin = minValue - range * 0.1; // 向下10%
            yAxisMax = maxValue + range * 0.1; // 向上10%
          }
        }
        
        // 确保最小值不会小于0
        yAxisMin = Math.max(0, yAxisMin);
        
        console.log('前复权切换后计算的Y轴范围:', {minValue, maxValue, range, yAxisMin, yAxisMax});
        
        // 更新图表的Y轴范围
        equityChart.setOption({
          yAxis: {
            min: yAxisMin,
            max: yAxisMax
          }
        }, false); // 使用false避免强制重绘，让ECharts自动处理
      }
    }
  });
}

// 显示资金曲线
async function handleShowEquityChart() {
  console.log('显示资金曲线，查询参数:', queryParams);
  
  // 重置前复权状态
  isFilled.value = false
  originalData.value = null
  
  // 清除之前的数据，确保显示最新数据
  equityChartData.value = {
    dates: [],
    hyEquity: [],
    hsEquity: [],
    totalEquity: [],
    hyWithdrawalDepositTotal: [],
    hsWithdrawalDepositTotal: []
  };
  
  chartDialogVisible.value = true
  await nextTick()
  const success = await fetchEquityChartData()
  if (success) {
    console.log('数据获取成功，初始化图表');
    // 每次显示时都重新初始化图表，确保Y轴范围适应最新数据
    initEquityChart();
    
    // 确保图表已初始化
    if (equityChart) {
      // 收集当前可见系列的数据（基于保存的图例选择状态）
      const visibleValues = [];
      
      if (legendSelectionState.value['hy账户']) {
        visibleValues.push(...equityChartData.value.hyEquity);
      }
      if (legendSelectionState.value['hs账户']) {
        visibleValues.push(...equityChartData.value.hsEquity);
      }
      if (legendSelectionState.value['合计']) {
        visibleValues.push(...equityChartData.value.totalEquity);
      }
      
      console.log('图表显示后的可见数据:', visibleValues);
      
      // 如果有可见数据，重新计算Y轴范围，确保精确显示
      if (visibleValues.length > 0 && !visibleValues.every(v => v === 0)) {
        // 基于可见数据重新计算Y轴范围
        const minValue = Math.min(...visibleValues);
        const maxValue = Math.max(...visibleValues);
        const range = maxValue - minValue;
        
        // 计算新的Y轴范围
        let yAxisMin, yAxisMax;
        
        if (range === 0) {
          // 处理所有值都相同的情况
          const baseValue = minValue || 10000; // 避免0值
          yAxisMin = baseValue * 0.9; // 向下10%
          yAxisMax = baseValue * 1.1; // 向上10%
        } else {
          // 根据数据变化幅度动态调整扩展比例
          const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
          
          if (variationRatio < 0.01) { // 变化小于1%
            // 数据变化非常小，需要更大的扩展比例
            yAxisMin = minValue - range * 0.5; // 向下50%
            yAxisMax = maxValue + range * 0.5; // 向上50%
          } else if (variationRatio < 0.05) { // 变化小于5%
            // 数据变化较小，适度扩展
            yAxisMin = minValue - range * 0.3; // 向下30%
            yAxisMax = maxValue + range * 0.3; // 向上30%
          } else {
            // 正常数据范围
            yAxisMin = minValue - range * 0.1; // 向下10%
            yAxisMax = maxValue + range * 0.1; // 向上10%
          }
        }
        
        // 确保最小值不会小于0
        yAxisMin = Math.max(0, yAxisMin);
        
        console.log('图表显示后计算的Y轴范围:', {minValue, maxValue, range, yAxisMin, yAxisMax});
        
        // 更新图表的Y轴范围
        equityChart.setOption({
          yAxis: {
            min: yAxisMin,
            max: yAxisMax
          }
        }, false); // 使用false避免强制重绘，让ECharts自动处理
      }
    }
  }
}

// 监听账户/品种变化，当账户代码发生变化时重新计算Y轴范围
async function refreshChartWithNewAccount() {
  console.log('刷新图表数据，当前查询参数:', queryParams);
  
  // 确保对话框可见
  if (chartDialogVisible.value) {
    // 安全策略：先销毁现有图表实例，避免状态冲突
    if (equityChart) {
      equityChart.dispose();
      equityChart = null;
    }
    
    // 清除之前的数据，避免混合显示
    equityChartData.value = {
      dates: [],
      hyEquity: [],
      hsEquity: [],
      totalEquity: [],
      hyWithdrawalDepositTotal: [],
      hsWithdrawalDepositTotal: []
    };
    
    console.log('开始获取新的图表数据');
    const success = await fetchEquityChartData()
    
    if (success) {
      console.log('获取数据成功，重新初始化图表');
      // 等待DOM更新后再初始化图表
      nextTick(() => {
        try {
          // 重新初始化图表，计算新的Y轴范围
          initEquityChart();
          console.log('图表重新初始化成功');
          
          // 确保图表已初始化
          if (equityChart) {
            // 收集当前可见系列的数据（基于保存的图例选择状态）
            const visibleValues = [];
            
            if (legendSelectionState.value['hy账户']) {
              visibleValues.push(...equityChartData.value.hyEquity);
            }
            if (legendSelectionState.value['hs账户']) {
              visibleValues.push(...equityChartData.value.hsEquity);
            }
            if (legendSelectionState.value['合计']) {
              visibleValues.push(...equityChartData.value.totalEquity);
            }
            
            console.log('账户变更后的可见数据:', visibleValues);
            
            // 如果有可见数据，重新计算Y轴范围，确保精确显示
            if (visibleValues.length > 0 && !visibleValues.every(v => v === 0)) {
              // 基于可见数据重新计算Y轴范围
              const minValue = Math.min(...visibleValues);
              const maxValue = Math.max(...visibleValues);
              const range = maxValue - minValue;
              
              // 计算新的Y轴范围
              let yAxisMin, yAxisMax;
              
              if (range === 0) {
                // 处理所有值都相同的情况
                const baseValue = minValue || 10000; // 避免0值
                yAxisMin = baseValue * 0.9; // 向下10%
                yAxisMax = baseValue * 1.1; // 向上10%
              } else {
                // 根据数据变化幅度动态调整扩展比例
                const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
                
                if (variationRatio < 0.01) { // 变化小于1%
                  // 数据变化非常小，需要更大的扩展比例
                  yAxisMin = minValue - range * 0.5; // 向下50%
                  yAxisMax = maxValue + range * 0.5; // 向上50%
                } else if (variationRatio < 0.05) { // 变化小于5%
                  // 数据变化较小，适度扩展
                  yAxisMin = minValue - range * 0.3; // 向下30%
                  yAxisMax = maxValue + range * 0.3; // 向上30%
                } else {
                  // 正常数据范围
                  yAxisMin = minValue - range * 0.1; // 向下10%
                  yAxisMax = maxValue + range * 0.1; // 向上10%
                }
              }
              
              // 确保最小值不会小于0
              yAxisMin = Math.max(0, yAxisMin);
              
              console.log('账户变更后计算的Y轴范围:', {minValue, maxValue, range, yAxisMin, yAxisMax});
              
              // 更新图表的Y轴范围
              equityChart.setOption({
                yAxis: {
                  min: yAxisMin,
                  max: yAxisMax
                }
              }, false); // 使用false避免强制重绘，让ECharts自动处理
            }
          }
        } catch (e) {
          console.error('图表初始化失败，将尝试重试:', e);
          // 失败时尝试重试一次
          setTimeout(() => {
            try {
              initEquityChart();
              console.log('图表重新初始化重试成功');
            } catch (retryError) {
              console.error('图表重新初始化重试失败:', retryError);
              ElMessage.error('图表更新失败，请尝试关闭对话框后重新打开');
            }
          }, 200);
        }
      });
    } else {
      console.log('获取数据失败');
    }
  } else {
    console.log('图表对话框未打开，跳过刷新');
  }
}

// 切换全屏显示
function toggleFullscreen() {
  isFullscreen.value = !isFullscreen.value
  
  // 切换全屏类后，等待DOM更新完成再重新创建图表
  nextTick(() => {
    // 安全策略：先销毁当前图表，确保清除所有状态
    if (equityChart) {
      equityChart.dispose()
      equityChart = null
    }
    
    // 获取图表容器和DOM元素
    const chartContainer = document.querySelector('.chart-container')
    const equityChartElement = document.getElementById('equityChart')
    
    // 从非全屏切换到全屏时，强制设置全屏样式
    if (isFullscreen.value && chartContainer && equityChartElement) {
      // 强制设置全屏样式
      chartContainer.style.position = 'fixed'
      chartContainer.style.top = '0'
      chartContainer.style.left = '0'
      chartContainer.style.width = '100vw'
      chartContainer.style.height = '100vh'
      chartContainer.style.zIndex = '9999'
      chartContainer.style.backgroundColor = '#fff'
      chartContainer.style.padding = '20px'
      chartContainer.style.boxSizing = 'border-box'
      
      // 强制设置图表元素样式
      equityChartElement.style.height = 'calc(100vh - 60px)'
      
      // 强制重排和重绘
      void chartContainer.offsetWidth
      void equityChartElement.offsetWidth
    }
    // 从全屏切换回非全屏时，强制重置容器和图表大小
    else if (!isFullscreen.value && chartContainer && equityChartElement) {
      // 强制重置容器样式，清除全屏模式下的样式影响
      chartContainer.style.position = 'relative'
      chartContainer.style.width = '100%'
      chartContainer.style.height = '400px'
      chartContainer.style.zIndex = '1'
      chartContainer.style.background = 'transparent'
      chartContainer.style.padding = '0'
      
      // 强制重置图表元素样式
      equityChartElement.style.width = '100%'
      equityChartElement.style.height = '400px'
      
      // 强制重排和重绘
      void chartContainer.offsetWidth
      void equityChartElement.offsetWidth
    }
    
    console.log('开始重新初始化图表以适应新的容器尺寸');
    
    // 重新初始化图表，确保正确适应新的容器尺寸
    initEquityChart()
    
    // 如果前复权已启用，确保数据正确应用
    if (isFilled.value && originalData.value) {
      // 应用前复权数据
      const filledData = calculateForwardFilled();
      if (filledData) {
        equityChartData.value = {
          dates: [...filledData.dates],
          hyEquity: [...filledData.hyEquity],
          hsEquity: [...filledData.hsEquity],
          totalEquity: [...filledData.totalEquity],
          hyWithdrawalDepositTotal: [...filledData.hyWithdrawalDepositTotal],
          hsWithdrawalDepositTotal: [...filledData.hsWithdrawalDepositTotal]
        };
        // 再次初始化图表以显示更新后的数据
        console.log('应用前复权数据后重新初始化图表');
        initEquityChart();
      }
    }
    
    // 安全resize策略：避免访问未初始化的coordinateSystem
    const safeResize = () => {
      if (!equityChart) return;
      
      try {
        equityChart.resize();
        console.log('安全resize操作成功完成');
        return true;
      } catch (e) {
        console.error('安全resize操作失败，将尝试重新初始化:', e);
        // 发生错误时，尝试重新初始化图表
        try {
          equityChart.dispose();
          equityChart = null;
          const chartDom = document.getElementById('equityChart');
          if (chartDom) {
            equityChart = echarts.init(chartDom);
            initEquityChart();
            return true;
          }
        } catch (reInitError) {
          console.error('重新初始化图表失败:', reInitError);
        }
        return false;
      }
    };
    
    // 优化后的resize策略，避免频繁调用可能导致问题的handleLegendSelectChanged
    if (!isFullscreen.value) {
      console.log('从全屏切换到非全屏，准备安全resize');
      // 使用更合理的延迟策略，确保DOM完全更新
      setTimeout(() => {
        if (safeResize()) {
          // 只有第一次resize成功才继续后续操作
          setTimeout(() => {
            safeResize();
          }, 300)
        }
      }, 200)
    } else {
      console.log('从非全屏切换到全屏，准备安全resize');
      setTimeout(() => {
        safeResize();
      }, 150)
    }
  })
}

// 关闭资金曲线对话框
function handleChartDialogClose() {
  // 确保退出全屏状态
  if (isFullscreen.value) {
    isFullscreen.value = false
  }
  
  chartDialogVisible.value = false
  if (equityChart) {
    equityChart.dispose()
    equityChart = null
  }
}

// 导出
function handleExport() {
  // 使用驼峰命名参数
  const exportParams = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    accountCode: queryParams.accountCode,
    beginDate: queryParams.beginDate,
    endDate: queryParams.endDate
  }
  exportFutureAccountDaily(exportParams).then(response => {
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `期货账户资金日报_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  }).catch(error => {
    console.error('导出期货账户资金日报失败:', error)
    ElMessage.error('导出期货账户资金日报失败，请稍后重试')
  })
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadAccountList()
  getList()
})
</script>

<style scoped>
.compact-form .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.compact-form .el-form-item__content {
  margin-left: 5px !important;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}

/* 图表容器样式 */
.chart-container {
  position: relative;
  width: 100%;
  height: 400px;
  transition: all 0.3s ease;
}

/* 全屏状态样式 */
.chart-container.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.chart-container.fullscreen #equityChart {
  height: calc(100vh - 60px) !important;
}

/* 图表头部样式 */
.chart-header {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 100;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 8px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 全屏模式下确保控件位置适当 */
.chart-container.fullscreen .chart-header {
  top: 30px;
  right: 30px;
  z-index: 10000;
  background-color: rgba(255, 255, 255, 0.95);
}
</style>